class ImageCompressor {
    constructor() {
        this.files = [];
        this.processedFiles = [];
        this.totalOriginalSize = 0;
        this.totalCompressedSize = 0;
        
        this.initializeElements();
        this.bindEvents();
        this.setupDragAndDrop();
    }

    initializeElements() {
        // 获取DOM元素
        this.dropZone = document.getElementById('dropZone');
        this.fileInput = document.getElementById('fileInput');
        this.selectBtn = document.getElementById('selectBtn');
        this.filesSection = document.getElementById('filesSection');
        this.filesList = document.getElementById('filesList');
        this.actionButtons = document.getElementById('actionButtons');
        this.downloadAllBtn = document.getElementById('downloadAllBtn');
        this.statsCard = document.getElementById('statsCard');
        this.statsPercentage = document.getElementById('statsPercentage');
        this.statsTotalSize = document.getElementById('statsTotalSize');
        this.toast = document.getElementById('toast');
        this.loadingOverlay = document.getElementById('loadingOverlay');
    }

    bindEvents() {
        // 绑定事件监听器
        this.selectBtn.addEventListener('click', (e) => {
            e.stopPropagation();
            this.fileInput.click();
        });
        
        this.fileInput.addEventListener('change', (e) => this.handleFileSelect(e));
        this.downloadAllBtn.addEventListener('click', () => this.downloadAll());
        
        // 点击拖放区域也触发文件选择
        this.dropZone.addEventListener('click', (e) => {
            if (e.target === this.dropZone || e.target.closest('.drop-content')) {
                this.fileInput.click();
            }
        });
    }

    setupDragAndDrop() {
        // 设置拖放功能
        ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
            this.dropZone.addEventListener(eventName, this.preventDefaults, false);
            document.body.addEventListener(eventName, this.preventDefaults, false);
        });

        ['dragenter', 'dragover'].forEach(eventName => {
            this.dropZone.addEventListener(eventName, () => this.highlight(), false);
        });

        ['dragleave', 'drop'].forEach(eventName => {
            this.dropZone.addEventListener(eventName, () => this.unhighlight(), false);
        });

        this.dropZone.addEventListener('drop', (e) => this.handleDrop(e), false);
    }

    preventDefaults(e) {
        e.preventDefault();
        e.stopPropagation();
    }

    highlight() {
        this.dropZone.classList.add('dragover');
    }

    unhighlight() {
        this.dropZone.classList.remove('dragover');
    }

    handleDrop(e) {
        const dt = e.dataTransfer;
        const files = dt.files;
        this.processFiles(files);
    }

    handleFileSelect(e) {
        const files = e.target.files;
        this.processFiles(files);
    }

    processFiles(files) {
        const fileArray = Array.from(files);
        
        // 验证文件
        const validFiles = fileArray.filter(file => {
            if (!file.type.startsWith('image/')) {
                this.showToast('只支持图片文件', 'error');
                return false;
            }
            if (file.size > 5 * 1024 * 1024) { // 5MB
                this.showToast('文件大小不能超过5MB', 'error');
                return false;
            }
            return true;
        });

        if (validFiles.length === 0) return;

        // 检查文件数量限制
        if (this.files.length + validFiles.length > 20) {
            this.showToast('最多只能处理20张图片', 'error');
            return;
        }

        // 添加文件到列表
        validFiles.forEach(file => {
            const fileData = {
                    id: Date.now() + Math.random(),
                    file: file,
                name: file.name,
                    originalSize: file.size,
                compressedSize: 0,
                progress: 0,
                status: 'waiting', // waiting, processing, completed, error
                compressedBlob: null
            };
            this.files.push(fileData);
            this.renderFileItem(fileData);
        });

        this.showFilesSection();
        this.startCompression();
    }

    showFilesSection() {
        this.filesSection.style.display = 'block';
        // 保持拖放区域可见，但使用紧凑模式
        this.dropZone.classList.add('compact');
    }

    renderFileItem(fileData) {
        const fileItem = document.createElement('div');
        fileItem.className = 'file-item';
        fileItem.dataset.fileId = fileData.id;
        
        fileItem.innerHTML = `
            <div class="file-name">${fileData.name}</div>
            <div class="file-original-size">${this.formatFileSize(fileData.originalSize)}</div>
            <div class="file-progress">
                <div class="progress-bar" style="width: 0%"></div>
                <div class="progress-text">等待中...</div>
                </div>
            <div class="file-compressed-size">-</div>
            <div class="file-reduction">-</div>
            <div class="file-actions">
                <button class="download-btn" disabled>下载</button>
            </div>
        `;
        
        this.filesList.appendChild(fileItem);
    }

    async startCompression() {
        // 移除全屏加载遮罩
        // this.showLoading('正在压缩图片...');
        
        for (const fileData of this.files) {
            if (fileData.status === 'waiting') {
                await this.compressFile(fileData);
            }
        }
        
        // this.hideLoading();
        this.updateStats();
        this.showActionButtons();
    }

    async compressFile(fileData) {
        try {
            fileData.status = 'processing';
            this.updateFileProgress(fileData, 10, '正在处理...');

            // 使用默认压缩设置
            const options = {
                quality: 0.8,
                maxWidth: 1920,
                maxHeight: 1080,
                convertSize: 1000000, // 1MB以上的文件转换为JPEG
            };

            // 动态导入压缩库
            if (!window.imageCompression) {
                const script = document.createElement('script');
                script.src = 'browser-image-compression.min.js';
                document.head.appendChild(script);
                await new Promise(resolve => script.onload = resolve);
            }

            this.updateFileProgress(fileData, 50, '压缩中...');

            // 压缩图片
            const compressedFile = await imageCompression(fileData.file, options);
            
            fileData.compressedSize = compressedFile.size;
            fileData.compressedBlob = compressedFile;
            fileData.status = 'completed';
            
            this.updateFileProgress(fileData, 100, 'Finished');
            this.updateFileReduction(fileData);
            this.enableDownload(fileData);
            
        } catch (error) {
            console.error('压缩失败:', error);
            fileData.status = 'error';
            this.updateFileProgress(fileData, 0, '压缩失败');
            this.showToast('压缩失败: ' + fileData.name, 'error');
        }
    }

    updateFileProgress(fileData, progress, text) {
        const fileItem = document.querySelector(`[data-file-id="${fileData.id}"]`);
        if (!fileItem) return;

        const progressBar = fileItem.querySelector('.progress-bar');
        const progressText = fileItem.querySelector('.progress-text');
        
        progressBar.style.width = progress + '%';
        progressText.textContent = text;
        
        if (progress === 100) {
            progressBar.style.background = '#27ae60';
        }
    }

    updateFileReduction(fileData) {
        const reduction = Math.round((1 - fileData.compressedSize / fileData.originalSize) * 100);
        const fileItem = document.querySelector(`[data-file-id="${fileData.id}"]`);
        if (!fileItem) return;

        const reductionElement = fileItem.querySelector('.file-reduction');
        reductionElement.textContent = `-${reduction}%`;
        
        // 更新压缩后文件大小显示
        const compressedSizeElement = fileItem.querySelector('.file-compressed-size');
        compressedSizeElement.textContent = this.formatFileSize(fileData.compressedSize);
    }

    enableDownload(fileData) {
        const fileItem = document.querySelector(`[data-file-id="${fileData.id}"]`);
        if (!fileItem) return;

        const downloadBtn = fileItem.querySelector('.download-btn');
        downloadBtn.disabled = false;
        downloadBtn.addEventListener('click', () => this.downloadFile(fileData));
    }

    downloadFile(fileData) {
        if (!fileData.compressedBlob) return;
        
        const url = URL.createObjectURL(fileData.compressedBlob);
        const a = document.createElement('a');
        a.href = url;
        a.download = this.getCompressedFileName(fileData.name);
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }

    getCompressedFileName(originalName) {
        const lastDotIndex = originalName.lastIndexOf('.');
        const nameWithoutExt = originalName.substring(0, lastDotIndex);
        const ext = originalName.substring(lastDotIndex);
        return `${nameWithoutExt}_compressed${ext}`;
    }

    showActionButtons() {
        this.actionButtons.style.display = 'flex';
    }

    updateStats() {
        this.totalOriginalSize = this.files.reduce((sum, file) => sum + file.originalSize, 0);
        this.totalCompressedSize = this.files.reduce((sum, file) => sum + (file.compressedSize || 0), 0);
        
        const reduction = Math.round((1 - this.totalCompressedSize / this.totalOriginalSize) * 100);
        
        this.statsPercentage.textContent = `${reduction}%`;
        this.statsTotalSize.textContent = this.formatFileSize(this.totalCompressedSize);
        this.statsCard.style.display = 'block';
    }

    async downloadAll() {
        const completedFiles = this.files.filter(file => file.status === 'completed');
        if (completedFiles.length === 0) {
            this.showToast('没有可下载的文件', 'warning');
                return;
            }
            
        // 如果只有一个文件，直接下载
        if (completedFiles.length === 1) {
            this.downloadFile(completedFiles[0]);
            return;
        }

        // 多个文件，创建ZIP（简化实现：逐个下载）
        this.showToast('开始下载所有文件...', 'success');
        for (const file of completedFiles) {
            await new Promise(resolve => setTimeout(resolve, 200)); // 小延迟
            this.downloadFile(file);
    }
    }

    formatFileSize(bytes) {
        if (bytes === 0) return '0 B';
        const k = 1024;
        const sizes = ['B', 'KB', 'MB', 'GB'];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i];
    }

    showToast(message, type = 'success') {
        this.toast.textContent = message;
        this.toast.className = `toast ${type}`;
        this.toast.classList.add('show');
        
        setTimeout(() => {
            this.toast.classList.remove('show');
        }, 3000);
    }

    showLoading(text = '处理中...') {
        this.loadingOverlay.querySelector('.loading-text').textContent = text;
        this.loadingOverlay.style.display = 'flex';
    }

    hideLoading() {
        this.loadingOverlay.style.display = 'none';
    }
}

// 初始化应用
document.addEventListener('DOMContentLoaded', () => {
    new ImageCompressor();
}); 